<!DOCTYPE html>
<html lang="en">
  <!---
模型操作
1、实现整个的自动居中和自动满屏
2、在多个模型种，选择一个模型进行编辑
a.实现
-->

  <head>
    <meta charset="UTF-8">
    <title>cube-oper</title>
    <script type="importmap">
        {
          "imports": {
            "three": "./js/threejs/three.module.js",
            "three/addons/": "./js/threejs/jsm/",
            "Vue": "./js/vue@3.5.13.js"
          }
        }
    </script>
    <script src="./js/pointUtil.js"></script>
    <!-- <script src="./js/three-scene.js"></script> -->
    <style>
    body {
      margin: 0;
      background-color: #000;
      color: #fff;
      font-family: Monospace;
      font-size: 13px;
      line-height: 24px;
      overscroll-behavior: none;
    }

    canvas {
      display: block;
    }
    #app{
      position: relative;
    }

    #tooltip {
      position: absolute;
      background-color: rgba(0, 0, 0, 0.7);
      color: white;
      padding: 5px;
      border-radius: 5px;
      display: none;
      /* 默认隐藏 */
      pointer-events: none;
      font-size: 12px;
      white-space: break-spaces;
      z-index: 1;
    }
    #panel{
      width: 350px;
      height: 100%;
      position: absolute;
      right: 0;
      top: 0;
      background-color: #fff;
      padding: 8px;
      box-sizing: border-box;
      z-index: 1;
      color: #666;
    }
    .hide{
      display: none;
    }
    .prop{
      display: flex;
      padding: 8px 0;
    }
    .prop .label{
      flex: 0 0 4rem;
    }
    .prop .value{
      display: flex;
      gap: 10px;
      flex: 0 0 calc(100% - 4rem);
      overflow: auto;
    }
    .prop .value input{
      width: 75px;
    }
  </style>
  </head>

  <body>
    <!-- 创建用于显示提示的文本元素 -->
    <div id="app">
      <div id="container"></div>
      <div id="tooltip" onclick="tooltipCkick"></div>
      <div id="panel" class="hide">
        <div style="display: flex; justify-content: end;" id="close">
          <svg t="1732021458373" class="icon" viewBox="0 0 1024 1024"
            version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1975"
            width="32" height="32"><path
              d="M874.057143 149.942857a512 512 0 1 0 0 724.114286 512 512 0 0 0 0-724.114286zM687.908571 636.16a25.782857 25.782857 0 0 1 0 36.571429l-15.542857 15.542857a25.782857 25.782857 0 0 1-36.571428 0L512 563.748571l-124.16 124.16a25.782857 25.782857 0 0 1-36.571429 0l-15.542857-15.542857a25.782857 25.782857 0 0 1 0-36.571428L460.251429 512l-124.16-124.16a25.782857 25.782857 0 0 1 0-36.571429l15.542857-15.542857a25.782857 25.782857 0 0 1 36.571428 0L512 460.251429l124.16-124.16a25.782857 25.782857 0 0 1 36.571429 0l15.542857 15.542857a25.782857 25.782857 0 0 1 0 36.571428L563.748571 512z"
              fill="#515151" p-id="1976"></path></svg>
        </div>
        <div class="prop">
          <div class="label">类型</div>
          <div class="value" id="meshtype"></div>
        </div>
        <div class="prop">
          <div class="label">userData</div>
          <div class="value" id="userdata"></div>
        </div>
        <div class="prop">
          <div class="label">位置</div>
          <div class="value">
            <input class="property" type="number" id="posx" width="25px" />
            <input class="property" type="number" id="posy" width="25px" />
            <input class="property" type="number" id="posz" width="25px" />
          </div>
        </div>
        <div class="prop">
          <div class="label">旋转(°)</div>
          <div class="value">
            <input class="property" type="number" id="rotax" width="25px" />
            <input class="property" type="number" id="rotay" width="25px" />
            <input class="property" type="number" id="rotaz" width="25px" />
          </div>
        </div>
        <div class="prop">
          <div class="label">自身旋转</div>
          <div class="value">
            <input class="property" type="number" id="rotaslfx" width="25px" />
            <input class="property" type="number" id="rotaslfy" width="25px" />
            <input class="property" type="number" id="rotaslfz" width="25px" />
          </div>
        </div>
        <div class="prop">
          <div class="label">隐藏</div>
          <div class="value">
            <input class="property" type="checkbox" id="visable" width="25px" />
          </div>
        </div>
      </div>
    </div>
    <script type="module">
    import * as THREE from "./js/threejs/three.module.js";
    import threeUtil from './js/three-cube.js';
    import { Drager } from './js/drag.js'

    import { add } from './js/add.js'

    import * as common from './js/three-comm.js'
    import { VertexNormalsHelper } from 'three/addons/helpers/VertexNormalsHelper.js';
    
    // 索引数组，定义每个面由哪些顶点构成 (每个面由两个三角形组成)
    const indicesCube = [
      0, 1, 2, 0, 2, 3, // 底面
      4, 6, 5, 4, 7, 6, // 顶面
      0, 4, 5, 0, 5, 1, // 右面
      1, 5, 6, 1, 6, 2, // 前面
      2, 6, 7, 2, 7, 3, // 上面
      3, 7, 4, 3, 4, 0, // 背面
    ];


    var optCubes = [
      { "data": { "id": "101", "type": "L", "name": "L01", "color": "#FF0000" }, "points": [{ "x": 20, "y": 0 }, { "x": 190, "y": 0 }, { "x": 190, "y": 20 }, { "x": 20, "y": 20 }] },
      { "data": { "id": "101", "type": "Z", "name": "L02", "color": "#A52A2A" }, "points": [{ "x": 190, "y": 0 }, { "x": 240, "y": 50 }, { "x": 220, "y": 50 }, { "x": 190, "y": 20 }] },
      { "data": { "id": "101", "type": "L", "name": "L03", "color": "#5F9EA0" }, "points": [{ "x": 220, "y": 50 }, { "x": 240, "y": 50 }, { "x": 240, "y": 150 }, { "x": 220, "y": 150 }] },
      { "data": { "id": "101", "type": "Z", "name": "L04", "color": "#7FFF00" }, "points": [{ "x": 150, "y": 150 }, { "x": 240, "y": 150 }, { "x": 220, "y": 170 }, { "x": 150, "y": 170 }] },
      { "data": { "id": "101", "type": "Z", "name": "Z01", "color": "#6495ED" }, "points": [{ "x": 130, "y": 150 }, { "x": 150, "y": 150 }, { "x": 150, "y": 170 }, { "x": 130, "y": 170 }] },
      { "data": { "id": "101", "type": "L", "name": "L05", "color": "#008B8B" }, "points": [{ "x": 50, "y": 150 }, { "x": 130, "y": 150 }, { "x": 130, "y": 170 }, { "x": 50, "y": 170 }] },
      { "data": { "id": "101", "type": "Z", "name": "L06", "color": "#006400" }, "points": [{ "x": 50, "y": 150 }, { "x": 50, "y": 170 }, { "x": 30, "y": 170 }, { "x": 30, "y": 160 }] },
      { "data": { "id": "101", "type": "L", "name": "L07", "color": "#8B008B" }, "points": [{ "x": 20, "y": 90 }, { "x": 50, "y": 150 }, { "x": 20, "y": 160 }, { "x": 0, "y": 100 }] },
      { "data": { "id": "101", "type": "Z", "name": "L08", "color": "#228B22" }, "points": [{ "x": 0, "y": 20 }, { "x": 20, "y": 0 }, { "x": 20, "y": 90 }, { "x": 0, "y": 100 }] },
      { "data": { "id": "101", "type": "L", "name": "L09", "color": "#FFA500" }, "points": [{ "x": 130, "y": 20 }, { "x": 150, "y": 20 }, { "x": 150, "y": 150 }, { "x": 130, "y": 150 }] },
      { "data": { "id": "101", "type": "DB", "name": "DB1", "color": "#FFA500" }, "points": [{ "x": 70, "y": 70 }, { "x": 90, "y": 70 }, { "x": 90, "y": 110 }, { "x": 70, "y": 110 }] },
      { "data": { "id": "101", "type": "DB", "name": "DB2", "color": "#4B0082" }, "points": [{ "x": 180, "y": 90 }, { "x": 200, "y": 90 }, { "x": 200, "y": 110 }, { "x": 180, "y": 110 }] },
      { "data": { "id": "101", "type": "LQ", "name": "L03", "color": "#5F9EA0" ,cg:5}, "points": [{ "x": -10-150, "y": 10 }, { "x": 30-150, "y": 40 }, { "x": 10-150, "y": 60 }, { "x": -30-150, "y": 30 }] }
    ];

    let { scene, camera, renderer, container, orbitControls, planeMesh} = threeUtil.initScene();

    var hCubes = []
    var hImgs = []
    var optCube = optCubes[0];
    var iCubeNum = optCubes.length
    var iCubeIdx
    const MOUSE_DOWN = "mouseDown";
    const MOUSE_MOVE = "mouseMove";
    const MOUSE_DOWN_MOVE = "mouseDownMove"; // 按下鼠标并移动
    const MOUSE_DOWNNO_MOVE = "mouseDownNoMove"; // 按下鼠标没有移动
    const MOUSE_NO = "mouseNo";

    var curSelectedMess = null;//当前选择模型
    let raycaster = new THREE.Raycaster();//选择模型的场景射线
    let pointer = new THREE.Vector2(); //鼠标点击的点
    let mouseSceneState = MOUSE_NO;
    var meshDragMarkers = [];//创建拖动的标志物
    var meshDragGroup = new THREE.Group()

    for (iCubeIdx = 0; iCubeIdx < iCubeNum; iCubeIdx++) {
      optCube = optCubes[iCubeIdx];
      threeUtil.addCube(optCube, hCubes, camera,scene)
    }

    let dragControls = threeUtil.regDrag(hCubes, camera, renderer,meshDragMarkers)

    let workArea = document.querySelector('#container')

    workArea.addEventListener('mouseup', onSceneMouseUp, false);
    workArea.addEventListener('mousedown', onSceneMouseDown, false);
    workArea.addEventListener('keydown', onScenekeyup, false);

    document.querySelector('#close').addEventListener('click',closepanel)

    let inputs = document.getElementsByClassName('property')
    Array.from(inputs).forEach(element => {
      element.addEventListener('change', onEdit)
    })

    const drager = new Drager(scene, camera, planeMesh, renderer, raycaster, pointer,orbitControls, dragControls, mouseSceneState)

    drager.regHover()

    function onEdit(event){
      let elm = event.target
      let id = elm.id
      let value = elm.value
      switch(id){
        case 'posx':
          curSelectedMess.object.position.x = value
          break;
        case 'posy':
          curSelectedMess.object.position.y = value
          break;
        case 'posz':
          curSelectedMess.object.position.z = value
          break;
        case 'rotax':
          curSelectedMess.object.rotation.x = value * Math.PI / 180
          break;
        case 'rotay':
          curSelectedMess.object.rotation.y = value * Math.PI / 180
          break;
        case 'rotaz':
          curSelectedMess.object.rotation.z = value * Math.PI / 180
          break;
        case 'rotaslfx':
          centerRota('X',value)
          break;
        case 'rotaslfy':
          centerRota('Y',value)
          break;
        case 'rotaslfz':
          centerRota('Z',value)
          break;
        
        case 'visable':
          curSelectedMess.object.visible = !elm.checked
          break;
      }

      curSelectedMess.object.updateMatrix()
    }

    //
    function centerRota(axis, theta){
      let object = curSelectedMess.object
      var points = getMessPoints(curSelectedMess);
      var messCenterPoint = getCenterPoint(points);
      let point = new THREE.Vector3(messCenterPoint.x, messCenterPoint.y, messCenterPoint.z)
      let axisVer
      switch(axis){
        case 'X':
          axisVer = new THREE.Vector3(1, 0, 0)
          break;
        case 'Y':
          axisVer = new THREE.Vector3(0, 1, 0)
          break;
        case 'Z':
          axisVer = new THREE.Vector3(0, 0, 1)
          break;
      }
      theta = theta * Math.PI / 180
      rotateAboutPoint(object, point, axisVer, theta)
    }

    
    function rotateAboutPoint(obj, point, axis, theta, pointIsWorld = false){
      if(pointIsWorld){
          obj.parent.localToWorld(obj.position); // compensate for world coordinate
      }

      obj.position.sub(point); // remove the offset
      obj.position.applyAxisAngle(axis, theta); // rotate the POSITION
      obj.position.add(point); // re-add the offset

      if(pointIsWorld){
          obj.parent.worldToLocal(obj.position); // undo world coordinates compensation
      }

      obj.rotateOnAxis(axis, theta); // rotate the OBJECT
    }
    
    function onScenekeyup(event){
      var event   = event || window.event;  //标准化事件对象
      var keyCode = event.keyCode;
      var tKey = event.target || event.srcElement;  //获取发生事件的元素，兼容IE和DOM
      var ctrlKey = event.ctrlKey;
      var shiftKey = event.shiftKey;
      var altKey = event.altKey;

      if (ctrlKey && shiftKey && altKey) {  //如果同时按下Ctrl和Shift键
        return;
      }
      //没有选择模型退出
      if(null==curSelectedMess){
        return
      }
      //Left arrow（左箭头键）	37	Top arrow（上箭头键）	38  Right arrow（右箭头键）	39	Down arrow（下箭头键）	40
      //非箭头按钮退出
      if(keyCode<37 || keyCode>40){
        return;
      }
      var step = 5;
      var rotation = curSelectedMess.object.rotation
      //按住了Ctrl键，当前模型移动
      if (ctrlKey){
        if(keyCode==37){
          if(altKey){
            curSelectedMess.object.position.z -= step;
          }else {
            curSelectedMess.object.position.x -= step;
          }
        }else if(keyCode==38){
          if(altKey){
            curSelectedMess.object.position.z += step;
          }else{
            curSelectedMess.object.position.y += step;
          }
        }else if(keyCode==39){
          if(altKey){
            curSelectedMess.object.position.z += step;
          }else {
            curSelectedMess.object.position.x += step;
          }
        }else if(keyCode==40){
          if(altKey){
            curSelectedMess.object.position.z -= step;
          }else{
            curSelectedMess.object.position.y -= step;
          }
        }
        curSelectedMess.object.updateMatrix();
        return;
      }
      // 0              1              2          3               4       5
      // 底面          顶面           前面         后面          左面       右面
      //0   1  2  3    4  5  6  7   8  9  10 11 12  13 14 15 16 17 18 20  21  22 23 24 
      //[0, 1, 2, 3], [4, 5, 6, 7],[0, 1, 5, 4],[2, 3, 7, 6],[0, 3, 7, 4],[1, 2, 6, 5] 
      //            0         1        2        3          4         5         6        7
      var faceIdx = 1;
      //按住了Shift键，当前模型增加
      //Left arrow（左箭头键）	37	Top arrow（上箭头键）	38  Right arrow（右箭头键）	39	Down arrow（下箭头键）	40
      if (shiftKey){
        var opt = {};
        if(keyCode==37){
          if(altKey){
            opt.z = -step;
          }else {
            faceIdx = 5;
            opt.x = -step;
          }
        }else if(keyCode==38){
          if(altKey){
            opt.z = step;
          }else {
            faceIdx = 2;
            opt.y = step;
          }
        }else if(keyCode==39){
          if(altKey){
            opt.z = step;
          }else {
            faceIdx = 5;
            opt.x = step;
          }
        }else if(keyCode==40){
          if(altKey){
            opt.z = -step;
          }else {
            faceIdx = 2;
            opt.y = -step;
          }
        }
        adjustMessVertexsByFace(curSelectedMess,faceIdx,opt)
        curSelectedMess.object.updateMatrix();
        return;
      }
    }
    
    function createDragMarkers(hScene,dragMarkers){
      if(null==dragMarkers || dragMarkers.length>0){
        return dragMarkers;
      }
      var dragMarker;
      for(let i=0;i<6;i++) {
        var opt = {}
        opt.faceindex = i;
        opt.type="dragmarker"
        dragMarker = common.createDragMarker(hScene,opt);
        if(null==dragMarker){
          continue;
        }
        dragMarkers.push(dragMarker)
        meshDragGroup.add(dragMarker);
        hScene.add(meshDragGroup);
      }
      return dragMarkers;
    }

    //创建标记物
    createDragMarkers(scene,meshDragMarkers);
    
    

    function adjustMessVertexsByFace(hMess,faceIdx,opt){
      if(null==hMess || typeof(hMess)=="undefined"){
        return null;
      }
      if(null==opt || typeof(opt)=="undefined"){
        return null;
      }
      if(null==faceIdx || typeof(faceIdx)!="number" || faceIdx<0 || faceIdx>5){
        return;
      }
      var hGeometry = getMessGeometry(hMess);
      if(null==hGeometry || typeof(hGeometry)=="undefined"){
        return null;
      }
      const faces = [
            [0, 1, 2, 3],// 底面            
            [4, 5, 6, 7],// 顶面
            [0, 1, 5, 4],// 前面            
            [2, 3, 7, 6],// 后面            
            [0, 3, 7, 4],// 左面            
            [1, 2, 6, 5] // 右面
        ]; 
      var iIdxs = faces[faceIdx];
      var iSize = iIdxs.length
      var iIdx;
      for(var i=0;i<iSize;i++){
        iIdx = iIdxs[i];
        adjustMessVertexsByPoint(hMess,iIdx,opt);
      }
      hGeometry.verticesNeedUpdate = true;
      hGeometry.getAttribute('position').needsUpdate = true
      hGeometry.computeBoundingBox()
      //取得各个面以及面的中心点
      updateMessMarkerPoints(hMess);
    }
    function adjustMessVertexsByPoint(hMess,iIdx,opt){
      if(null==hMess || typeof(hMess)=="undefined"){
        return null;
      }
      if(null==opt || typeof(opt)=="undefined"){
        return null;
      }
      if(null==iIdx || typeof(iIdx)!="number" || iIdx<0 || iIdx>7){
        return;
      }
      var hGeometry = getMessGeometry(hMess);
      if(null==hGeometry || typeof(hGeometry)=="undefined"){
        return null;
      }
      if(null==hGeometry.attributes || typeof(hGeometry.attributes)=="undefined"){
        return null;
      }
      if(null==hGeometry.attributes.position || typeof(hGeometry.attributes.position)=="undefined"){
        return null;
      }
      var x = opt.x;
      var y = opt.y
      var z = opt.z;

      if(null==x || typeof(x)!="number"){
        x = null;
      }
      if(null==y || typeof(y)!="number"){
        y = null;
      }
      if(null==z || typeof(z)!="number"){
        z = null;
      }
      // 0              1             2            3             4         5
      // 底面          顶面           前面         后面          左面       右面
      // 0  1  2  3    4  5  6  7   8  9  10 11 12  13 14 15 16  17 18 19 20  21 22 23 
      //[0, 1, 2, 3], [4, 5, 6, 7],[0, 1, 5, 4],[2, 3, 7, 6],[0, 3, 7, 4],[1, 2, 6, 5] 
      //            0         1        2        3          4         5         6        7
      var pArr = [[0,8,16],[1,9,20],[2,12,21],[3,13,17],[4,11,19],[5,10,23],[6,15,22],[7,14,18]];
      var myAyy = pArr[iIdx]
      var iSize = myAyy.length;
      var vIdx;
      var iPos;
      var myPointArr = [];
      
      for(var i=0;i<iSize;i++){
        vIdx = myAyy[i]
        iPos = vIdx*3;
        if(null!=x ){
          hGeometry.attributes.position.array[iPos  ] += x;
        }
        if(null!=y){
          hGeometry.attributes.position.array[iPos+1] += y;
        }
        if(null!=z ){
          hGeometry.attributes.position.array[iPos+2] += z;
        }
      }
    }
    function modifyMessVertexsByPoint(hMess,iIdx,point){
      if(null==hMess || typeof(hMess)=="undefined"){
        return null;
      }
      if(null==point || typeof(point)=="undefined"){
        return null;
      }
      if(null==iIdx || typeof(iIdx)!="number" || iIdx<0 || iIdx>7){
        return;
      }
      var hGeometry = getMessGeometry(hMess);
      if(null==hGeometry || typeof(hGeometry)=="undefined"){
        return null;
      }
      if(null==hGeometry.attributes || typeof(hGeometry.attributes)=="undefined"){
        return null;
      }
      if(null==hGeometry.attributes.position || typeof(hGeometry.attributes.position)=="undefined"){
        return null;
      }
      
      
      var x = point.x;
      var y = point.y
      var z = point.z;
      // 底面          顶面           前面         后面          左面       右面
      //0   1  2  3    4  5  6  7   8  9  10 11 12  13 14 15 16 17 18 20  21  22 23 24 
      //[0, 1, 2, 3], [4, 5, 6, 7],[0, 1, 5, 4],[2, 3, 7, 6],[0, 3, 7, 4],[1, 2, 6, 5] 
      //            0         1        2        3          4         5         6        7
      var pArr = [[0,8,16],[1,9,21],[2,12,22],[3,13,17],[4,11,20],[5,10,24],[6,15,23],[7,14,18]];
      var myAyy = pArr[iIdx]
      var iSize = myAyy.length;
      var vIdx;
      var iPos;
      var myPointArr = [];
      
      for(var i=0;i<iSize;i++){
        vIdx = myAyy[i]
        iPos = vIdx*3;
        if(null!=point.x && typeof(point.x)=="number"){
          hGeometry.attributes.position[iPos  ] = point.x;
        }
        if(null!=point.y && typeof(point.y)=="number"){
          hGeometry.attributes.position[iPos+1] = point.y;
        }
        if(null!=point.z && typeof(point.z)=="number"){
          hGeometry.attributes.position[iPos+2] = point.z;
        }
      }
      //hGeometry.attributes.position
    }


    function vertexsToStr(vertexs){
      if(null==vertexs || typeof(vertexs)=="undefined"){
        return '';
      }
      var iSize = vertexs.length/3;
      var result = '';
      var x,y,z;
      for(var i=0;i<iSize;i++){
        x = vertexs[i*3];
        y = vertexs[i*3+1];
        z = vertexs[i*3+2];
        result += '{x:'+x+','+'y:'+y+',z:'+z+'}';
      }
      return result;
    }
    
    function setMessMarkers(hMess){
      if(null==hMess || typeof(hMess)=="undefined"){
        return;
      }
      var messType = getMessType(hMess);
      if('SphereGeometry'==messType){
        return
      }
      var points = getMessPoints(hMess);
      var facePoints;
      var centerPoint;
      var messCenterPoint = getCenterPoint(points);
      var curPostion = hMess.point;

      if(null!=meshDragGroup.children){
        var iChild = meshDragGroup.children.length;
        var hChild;
        for(var i=iChild-1;i>=0;i--){
          hChild = meshDragGroup.children[i];
          if(null==hChild || null==hChild.geometry){
            continue;
          }
          if('SphereGeometry'!=hChild.geometry.type){
            meshDragGroup.remove(hChild);
            continue;
          }
        }
      }
      meshDragGroup.visible = true
      hMess.object.add(meshDragGroup);
      //取得各个面以及面的中心点
      updateMessMarkerPoints(hMess);
    }

    function updateMessMarkerPoints(hMess){
      if(null==hMess || typeof(hMess)=="undefined"){
        return;
      }
      var points = getMessPoints(hMess);
      //取得各个面以及面的中心点
      for(var faceIdx=0;faceIdx<6;faceIdx++){
        var facePoints = getMessFacePoints(hMess,faceIdx,points);
        var centerPoint= getCenterPoint(facePoints);
        setMarkerPoint(meshDragMarkers,faceIdx,centerPoint);
      }
    }

    function sceneMouseClick(event){
      if(event.target.id == 'panel'){
        return
      }
      curSelectedMess = null
      //完成模型选择
      pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
      pointer.y = - (event.clientY / window.innerHeight) * 2 + 1;
      raycaster.setFromCamera(pointer, camera);
      // 计算物体和射线的焦点
      var intersects = raycaster.intersectObjects(scene.children);
      if (null==intersects || intersects.length<1) {
        return
      }
      var iSize = intersects.length
      var intersect;
      for(var iIdx = 0;iIdx<iSize;iIdx++){
        intersect = intersects[iIdx];
        if(null==intersect){
          continue;
        }
        if('Mesh'== intersect.object.type && intersect.object.userData.type != "plane"){
          curSelectedMess = intersect;
          var hGeometry = getMessGeometry(curSelectedMess);
          //console.log('vertexsToStr=',vertexsToStr(hGeometry.attributes.position.array))
          setMessMarkers(curSelectedMess);
          var userData = curSelectedMess.object.userData;
          if(null!=userData){
            //console.log('userData.data=',JSON.stringify(userData.data))
          }
          // const helper = new VertexNormalsHelper(curSelectedMess.object,20, 0x00ff00, 1);
          // scene.add( helper);
          break;
        }
      }
      togglePanel()
    }

    function togglePanel(){
      console.log(curSelectedMess)
      let panel = document.querySelector('#panel')
      if(curSelectedMess){
        panel.classList.remove('hide')

        let object = curSelectedMess.object


        document.querySelector("#meshtype").innerHTML = object.type
        document.querySelector("#userdata").innerHTML = JSON.stringify(object.userData)
        document.querySelector('#posx').value = object.position.x
        document.querySelector('#posy').value = object.position.y
        document.querySelector('#posz').value = object.position.z

        document.querySelector('#rotax').value = object.rotation.x * 180 / Math.PI
        document.querySelector('#rotay').value = object.rotation.y * 180 / Math.PI
        document.querySelector('#rotaz').value = object.rotation.z * 180 / Math.PI

        document.querySelector('#visable').checked = !object.visible

      }else{
        panel.classList.add('hide')
        meshDragGroup.visible = false
      }
    }

    function closepanel(){
      panel.classList.add('hide')
    }

    //场景中的按下鼠标
    function onSceneMouseDown(event){
      event.preventDefault();
      mouseSceneState = MOUSE_DOWN
      if(curSelectedMess!=null){
        drager.callDrag(curSelectedMess,event,adjustMessVertexsByFace)
      }
    }
    //场景中的松开鼠标
    function onSceneMouseUp(event){
      event.preventDefault();
      drager.release()
      if (mouseSceneState === MOUSE_DOWNNO_MOVE || mouseSceneState === MOUSE_DOWN){
        sceneMouseClick(event);
      }
      mouseSceneState = MOUSE_NO
      // dragControls.connect()
    }

    //创建拖动的标志物
    // function createDragMarker  (hScene,opt) {
    //   if(null==opt || typeof(opt)=="undefined"){
    //     opt = {}
    //   }
    //   const geometry = new THREE.SphereGeometry( 3, 32, 16 );
    //   const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
    //   var dragMarker =  new THREE.Mesh( geometry, material )
    //   dragMarker.visible = false;
    //   dragMarker.userData = {}
    //   hScene.add(dragMarker);
    //   return dragMarker;
    // }
    //设置标记物的位置
    function setMarkerPoint(hMarkers,iIdx,point){
      if(null==hMarkers || typeof(hMarkers)=="undefined" || !(hMarkers instanceof Array)){
        return;
      }
      if(null==point || typeof(point)=="undefined"){
        return;
      }
      if(null==iIdx || typeof(iIdx)!="number"){
        return;
      }
      var iSize = hMarkers.length;
      if(iIdx<0 || iIdx>=iSize){
        return;
      }
      
      var hMarker = hMarkers[iIdx]
      // 设置物体的位置
      hMarker.position.set(point.x, point.y, point.z);
      hMarker.visible = true
    }
    //取得模型的类别
    function getMessType(hMess){
      var hGeometry = getMessGeometry(hMess);
      if(null==hGeometry || typeof(hGeometry)=="undefined"){
        return null;
      }
      return hGeometry.type;
    }

    //取得模型的类别
    function getMessGeometry(hMess){
      if(null==hMess || typeof(hMess)=="undefined"){
        return null;
      }
      var hGeometry = null;
      try{
        hGeometry = hMess.geometry;
      }catch(ex){
        hGeometry = null;
      }
      if(null==hGeometry || typeof(hGeometry)=="undefined"){
        if(null==hMess.object || typeof(hMess.object)=="undefined"){
          return null;
        }
        try{
          hGeometry = hMess.object.geometry;
        }catch(ex){
          hGeometry = null;
        }        
      }
      return hGeometry;
    }

    //取得顶点中心点
    function getCenterPoint(points){
      if(null==points || !(points instanceof Array)){
        return null;
      }
      var iSize = points.length;
      var point;
      var iSum = 0;
      var xSum = 0;
      var ySum = 0;
      var zSum = 0;
      for(var iIdx=0;iIdx<iSize;iIdx++){
        point = points[iIdx];
        if(null==point){
          continue;
        }
        iSum ++;
        xSum = accAdd(xSum,point.x);
        ySum = accAdd(ySum,point.y);
        zSum = accAdd(zSum,point.z);
      }
      if(iSum<1){
        return null;
      }
      xSum = accDiv(xSum,iSum);
      ySum = accDiv(ySum,iSum);
      zSum = accDiv(zSum,iSum);
      return {x:xSum,y:ySum,z:zSum};
    }
    //取得模型[hMess]指定面[faceIdx]的点 , points可以回传模型的所有顶点  底面[0, 1, 2, 3] 顶面 [4, 5, 6, 7]
    function getMessFacePoints(hMess,faceIdx,points){
      if(null==hMess || typeof(hMess)=="undefined"){
        return;
      }
      if(null==faceIdx || typeof(faceIdx)!="number" || faceIdx<0 || faceIdx>=6){
        faceIdx = 0;
      }
      if(null==points || !(points instanceof Array) || points.length<1){
        points = getMessPoints(hMess);
      }
      if(null==points || !(points instanceof Array) || points.length<8){
        return null;
      }
      const faces = [
            [0, 1, 2, 3],// 底面            
            [4, 5, 6, 7],// 顶面            
            [0, 1, 5, 4],// 前面            
            [2, 3, 7, 6],// 后面            
            [0, 3, 7, 4],// 左面            
            [1, 2, 6, 5] // 右面
        ]; 
      var idxs = faces[faceIdx];
      var result = [];
      var point;
      idxs.forEach(idx => {
                point = points[idx]
                result.push(point);
            });
      return result;
    }

    //取得模型指定面的点
    function getMessVertexs(hMess){
      if(null==hMess || typeof(hMess)=="undefined"){
        return null;
      }
      if(null==hMess.object || typeof(hMess.object)=="undefined"){
        return null;
      }
      if(null==hMess.object.geometry || typeof(hMess.object.geometry)=="undefined"){
        return null;
      }
      if(null==hMess.object.geometry || typeof(hMess.object.geometry)=="undefined"){
        return null;
      }
      if(null==hMess.object.geometry.attributes || typeof(hMess.object.geometry.attributes)=="undefined"){
        return null;
      }
      if(null==hMess.object.geometry.attributes.position || typeof(hMess.object.geometry.attributes.position)=="undefined"){
        return null;
      }
      return hMess.object.geometry.attributes.position.array;
    }
    //取得模型指定面的点
    function getMessPoints(hMess){
      var vertexs = getMessVertexs(hMess);
      if(null==vertexs || !(vertexs instanceof Float32Array)){
        return null;
      }
      var point
      var result = [];
      for(var i=0;i<8;i++){
        point = vertexToPoint(vertexs,i);
        if(null==point){
          continue;
        }
        result.push(point);
      }
      return result;
    }
    //取得三维中的Vertice坐标转变为点坐标
    function vertexToPoint(vertexs,pointIdx){
      if(null==pointIdx || typeof(pointIdx)!="number"){
        return null;
      }
      if(null==vertexs || typeof(vertexs)=="undefined" || !(vertexs instanceof Float32Array)){
        return null;
      }
      var xIdx = pointIdx*3;
      var yIdx = xIdx + 1;
      var zIdx = xIdx + 2;
      var iSize = vertexs.length;
      if(zIdx>=iSize || zIdx<2){
        return null;
      }
      var x = vertexs[xIdx];
      var y = vertexs[yIdx];
      var z = vertexs[zIdx];
      return {x:x,y:y,z:z}
    }

    //精确计算
  // 两个浮点数求和
  function accAdd(num1,num2){
    var r1,r2,m;
    try{
      r1 = num1.toString().split('.')[1].length;
    }catch(e){
      r1 = 0;
    }
    try{
      r2=num2.toString().split(".")[1].length;
    }catch(e){
      r2=0;
    }
    m = Math.pow(10,Math.max(r1,r2));
    // return (num1*m+num2*m)/m;
    return Math.round(num1*m+num2*m)/m;
  }
  // 两个浮点数相减
  function accSub(num1,num2){
    var r1,r2,m;
    try{
      r1 = num1.toString().split('.')[1].length;
    }catch(e){
      r1 = 0;
    }
    try{
      r2=num2.toString().split(".")[1].length;
    }catch(e){
      r2=0;
    }
      m = Math.pow(10,Math.max(r1,r2));
      n =(r1>=r2)?r1:r2;
    return (Math.round(num1*m-num2*m)/m).toFixed(n);
  }
  // 两数相乘
  function accMul(num1,num2){
    var m=0,s1=num1.toString(),s2=num2.toString(); 
    try{m+=s1.split(".")[1].length}catch(e){};
    try{m+=s2.split(".")[1].length}catch(e){};
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
  }
  // 两数相除
  function accDiv(num1,num2){
    var t1,t2,r1,r2;
    try{
      t1 = num1.toString().split('.')[1].length;
    }catch(e){
      t1 = 0;
    }
    try{
      t2=num2.toString().split(".")[1].length;
    }catch(e){
      t2=0;
    }
    r1=Number(num1.toString().replace(".",""));
    r2=Number(num2.toString().replace(".",""));
    return (r1/r2)*Math.pow(10,t2-t1);
  }




  </script>

  </body>

</html>